<template>
  <a-card :bordered="false" style="width: 100%">
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <!-- table区域-begin -->
    <div>
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-94"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        :checkbox-config="checkboxConfig"
        v-bind="vexConfig"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <!-- 操作按钮区域 -->
        <template #toolbar_buttons>
          <div class="table-operator" style="border-top: 5px">
            <a-button @click="handleAdd" type="primary" v-has="'externalUser:add'">新增</a-button>
            <a-button @click="batchDel" type="primary" v-has="'externalUser:delete'">删除</a-button>
            <a-button type="primary" @click="handleExportXls('经销商用户导入模版')">模板下载</a-button>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader1"
                      :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary">导入</a-button>
            </a-upload>
            <a-button v-has="'externalUser:export'" @click="downExportXls('cust_user_service')">导出</a-button>
            <a-button v-has="'externalUser:untie'" :disabled="selectedRowKeys.length<=0" @click="uboundOpenId">微信解绑
            </a-button>
          </div>
        </template>
        <template #detail="{ row,rowIndex }">
          <a href='javascript:' @click="handleDetail(row)">{{ row.userName }}</a>
        </template>
        <template #avatarslot="{ row,rowIndex }">
          <a-avatar shape="square" :src="getAvatarView(row.avatar)" icon="user"/>
        </template>
        <template #roleCode="{ row,rowIndex }">
          {{ row.roleCode == 'null' ? '#' : text }}
        </template>
        <template #status="{ row,rowIndex }">
          <a-switch :checked="row.status" size="small" @change="handleStatus(row,$event)"/>
        </template>
        <template #action="{ row,rowIndex }">
          <a v-has="'externalUser:update'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多
              <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href='javascript:' @click="handleChangePassword(row)">修改密码</a>
              </a-menu-item>
              <a-menu-item v-has="'business:log'">
                <a href='javascript:' @click='handleBusiness("用户管理",row)'>日志</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync="ipagination.current"
            :page-size.sync="ipagination.pageSize"
            :total="ipagination.total"
            :pageSizes="ipagination.pageSizeOptions"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <user-modal ref="modalForm" @ok="modalFormOk"></user-modal>

    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>

    <sys-user-agent-modal ref="sysUserAgentModal"></sys-user-agent-modal>

    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/>
    <business-log ref="businessLog"></business-log>
    <ConfigModal ref="ConfigModal" @ok="saveUserRelation"></ConfigModal>
  </a-card>
</template>

<script>
  import UserModal from '@page-modules/UserModal'
  import ConfigModal from '@page-modules/ConfigModal'
  import PasswordModal from '@page-modules/PasswordModal'
  import { getAction, postAction, putAction, getFileAccessHttpUrl } from '@/api/manage'
  import { frozenBatch, queryDepartTreeList } from '@/api/api'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import SysUserAgentModal from '@page-modules/SysUserAgentModal'
  import JInput from '@/components/cn-form/JInput'
  import UserRecycleBinModal from '@page-modules/UserRecycleBinModal'
  import CnDictSelectTag from '@/components/dict/CnDictSelectTag'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  export default {
    name: 'UserList',
    mixins: [PageListMixin],
    components: {
      SysUserAgentModal,
      UserModal,
      PasswordModal,
      JInput,
      UserRecycleBinModal,
      ConfigModal,
      CnDictSelectTag
    },
    data() {
      return {
        tokenHeader1: { 'Authorization': 'Bearer ' + Vue.ls.get(ACCESS_TOKEN).access_token },
        treeData: [],
        description: '这是用户管理页面',
        queryParam: {},
        recycleBinVisible: false,
        searchConfig: [
          {
            type: 'input',
            name: 'userName',
            placeholder: '请输入账号查询'
          }, {
            type: 'input',
            name: 'realName',
            placeholder: '请输入真实姓名'
          }, {
            type: 'input',
            name: 'roleName',
            placeholder: '请输入角色名称'
          }
        ],
        columns: [
          { type: 'checkbox', width: 60, fixed: 'left' },
          {
            fixed: 'left',
            title: '用户账号',
            field: 'userName',
            minWidth: 80,
            slots: { default: 'detail' }
          },
          {
            title: '用户名称',
            minWidth: 80,
            field: 'realName'
          },
          {
            title: '用户类型',
            minWidth: 80,
            field: 'userType_dictText'
          },
          {
            title: '角色',
            minWidth: 80,
            field: 'roleNames'
          },
          {
            title: '创建人',
            minWidth: 80,
            field: 'createName'
          },
          {
            title: '创建时间',
            field: 'createTime',
            minWidth: 80

          },
          {
            title: '更新人',
            minWidth: 80,
            field: 'updateName'
          },
          {
            title: '更新时间',
            field: 'updateTime',
            minWidth: 80
          },
          {
            title: '状态',
            minWidth: 80,
            fixed: 'right',
            field: 'status',
            slots: { default: 'status' }
          },
          {
            title: '操作',
            field: 'action',
            fixed: 'right',
            slots: { default: 'action' },
            width: 120
          }
        ],
        isorter: {
          userType: 2,
          permflag: 'external_user_page_impl'
        },
        url: {
          syncUser: '/process/extActProcess/doSyncUser',
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
          delete: window._CONFIG['domianURL'] + '/cnUserController/deleteByid',
          deleteBatch: window._CONFIG['domianURL'] + '/cnUserController/deleteBatch',
          detail: window._CONFIG['domianURL'] + '/cnUserController/getUserByIdOrCode',
          exportXlsUrl: window._CONFIG['domianURL'] + '/cnUserController/downloadTemplateCustomer',
          importExcelUrl: window._CONFIG['domianURL'] + '/cnUserController/importTemplateCustomer',
          saveUserRelation: window._CONFIG['domianURL'] + '/cnUserController/saveUserRelation',
          openid: window._CONFIG['domianURL'] + '/cnUserController/uboundOpenIdByUser'
        }
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${this.url.importExcelUrl}`
      }
    },
    created() {
      this.loadTree()
    },
    methods: {
      loadTree() {
        var that = this
        queryDepartTreeList({ permflag: 'user_page_impl_add_org' }).then((res) => {
          if (res.success) {
            that.treeData = []
            let treeList = res.result
            for (let a = 0; a < treeList.length; a++) {
              let temp = treeList[a]
              temp.isLeaf = temp.leaf
              that.treeData.push(temp)
            }
          }
        })
      },
      saveUserRelation(params) {
        postAction(this.url.saveUserRelation, params).then(async (res) => {
          if (res.success) {
            this.$message.success(res.message)
            await this.loadData()
            this.$refs.ConfigModal.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.$refs.ConfigModal.confirmLoading = false
          //that.close();
        })
      },
      getAvatarView: function(avatar) {
        return getFileAccessHttpUrl(avatar)
      },
      // 行内切换状态
      async handleStatus(row, status) {
        let that = this
        this.loading = true
        await frozenBatch({ id: row.id, status: Number(status) }).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.onClearSelected()
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loadData()
        })
      },

      handleMenuClick(e) {
        if (e.key == 1) {
          this.batchFrozen('003')
        } else if (e.key == 2) {
          this.batchFrozen('009')
        }
      },
      handleFrozen: function(id, status, userName) {
        let that = this
        //TODO 后台校验管理员角色
        if ('admin' == userName) {
          that.$message.warning('管理员账号不允许此操作！')
          return
        }
        frozenBatch({ ids: id, status: status }).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData()
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChangePassword(row) {
        this.$refs.passwordmodal.show(row.userName, row.userType)
      },
      handleAgentSettings(userName) {
        this.$refs.sysUserAgentModal.agentSettings(userName)
        this.$refs.sysUserAgentModal.title = '用户代理人设置'
      },
      passwordModalOk() {
        //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
      },
      uboundOpenId() {
        let ids = this.selectedRowKeys + ''
        getAction(this.url.openid, { ids }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      handleAdd: function() {
        this.$refs.modalForm.edit({ userType: 2 })
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>

